
import java.util.*;
/**
 * TelegrafDB 测试类
 */
public class TelegrafDBTest {
    
    public static void main(String[] args) {
        TelegrafDB db = null;
        
        try {
            System.out.println("=== KaiwuDB Java Test ===");
            
            String configFile = args.length > 0 ? args[0] : "kwdb_jdk.ini";
            System.out.println("Use configuration file: " + configFile);
            
            db = new TelegrafDB(configFile);
            
            db.printConfig();
            
            //testTimeSeriesDB(db);
            
            testRelationalDB(db);
            
            System.out.println("=== test end ===");
            
        } catch (Exception e) {
            System.err.println("Test Failed: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (db != null) {
                try {
                    db.close();
                    System.out.println("Database connection has been closed!");
                } catch (Exception e) {
                    System.err.println("An error occurred while closing the database connection: " + e.getMessage());
                }
            }
        }
    }
    private static void testTimeSeriesDB(TelegrafDB db) {
        System.out.println("\n--- Time series database testing ---");
        
        try {
            String postData = "cpu_usage,host=server01,region=us-west usage=25.5,idle=74.5 1617885600000000000\n" +
                            "cpu_usage,host=server02,region=us-west used=8192,free=2048 1617885600000000000";
            
            int loginResult = db.login();
            if (loginResult == TelegrafDB.DBCI_OK) {
                System.out.println("Successfully logged in to the time-series database!");
                int insertResult = db.insertData(postData, TelegrafDB.MODE_AUTO_CREATE_TABLE);
                if (insertResult == TelegrafDB.DBCI_OK) {
                    System.out.println("Time series data insertion successful");
                } else {
                    System.out.println("Insertion of time series data failed: " + db.getLastError());
                }
            } else {
                System.out.println("Login failure in the time-series database: " + db.getLastError());
            }
            
        } catch (Exception e) {
            System.err.println("Test anomaly in time-series database: " + e.getMessage());
        }
    }
    
    private static void testRelationalDB(TelegrafDB db) {
        System.out.println("\n--- Relational database testing ---");
        
        try {
            int connStatus = db.connectInitDB("");
            if (connStatus == TelegrafDB.CONNECTION_OK) {
                System.out.println("Relational database connection successful!");
                testTableOperations(db);
                testDataOperations(db);
                testBatchInsertPerformance(db);
                db.disconnectFromDB();
                System.out.println("Database connection has been disconnected!");
                
            } else {
                System.out.println("Relational database connection failed: " + db.getLastError());
            }
            
        } catch (Exception e) {
            System.err.println("Relational database test exception: " + e.getMessage());
        }
    }
    
    private static void testTableOperations(TelegrafDB db) {
        String tableName = "test";
        String[] columns = {"id", "name", "height"};
        
        if (db.tableExists(tableName)) {
            System.out.println("Table: " + tableName + " already exists!");
        } else {
            System.out.println("Table: " + tableName + " not exist, starting to create.");
            
            if (db.createTableIfNotExists(tableName, columns, "id")) {
                System.out.println("Table created successfully!");
            } else {
                System.out.println("Table creation failed: " + db.getLastError());
                return;
            }
        }
        int rowCount = db.getRowCount(tableName);
        System.out.println("Table: " + tableName + " Records: " + rowCount);
    }

    private static void testDataOperations(TelegrafDB db) {
        String tableName = "test";

        Map<String, String> record = new HashMap<>();
        record.put("id", "1");
        record.put("name", "temperature_sensor");
        record.put("height", "23.5");
        
        if (db.insertToDB(tableName, record)) {
            System.out.println("Single data insertion succeeded!");
        } else {
            System.out.println("Single data insertion failed: " + db.getLastError());
        }

        String[] queryColumns = {"id", "name", "height"};
        String result = db.selectFromDB(tableName, queryColumns, "name LIKE '%sensor%'", "id DESC", 5);
        System.out.println("Query result: " + result);
    }
    
    private static void testBatchInsertPerformance(TelegrafDB db) {
        String tableName = "test";
        
        System.out.println("\n--- Bulk insertion performance test ---");
        
        int recordCount = 50; 
        List<Map<String, String>> testData = generateTestData(recordCount);
        
        System.out.println("generate " + recordCount + " Test data completed");
        
        long startTime = System.currentTimeMillis();
        
        boolean success = db.batchInsertToDB(tableName, testData);
        
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        
        if (success) {
            System.out.println("Batch insertion successful!");
            System.out.println("Insert " + recordCount + " time-consuming: " + duration + " ms");
            System.out.println("average speed: " + (recordCount * 1000.0 / duration) + " record/s");
            
            int newRowCount = db.getRowCount(tableName);
            System.out.println("Total record count after insertion: " + newRowCount);
        } else {
            System.out.println("Batch insertion failed: " + db.getLastError());
        }
    }

    private static List<Map<String, String>> generateTestData(int count) {
        List<Map<String, String>> data = new ArrayList<>();
        Random random = new Random();
        
        for (int i = 1; i <= count; i++) {
            Map<String, String> record = new HashMap<>();
            record.put("id", "1" + i);
            record.put("name", "sensor_" + (i % 100));
            record.put("height", String.format("%.2f", 20.0 + random.nextDouble() * 15.0));
            
            data.add(record);
           
        }
        
        return data;
    }
}